package com.sun.kafka.consumer;

import com.sun.kafka.service.MessageService;
import com.sun.kafka.thread.MessageTask;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 多线程消费多个Topic数据
 */
@Slf4j
@Component
public class KafkaBatchListener {

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    private MessageService messageService;

    // Spring的SpEl表达式
    @KafkaListener(topics = { "#{'${monitor.kafka.topics}'.split(',')}" }, containerFactory = "batchFactory")
    public void listenPartitions(List<ConsumerRecord<String, String>> records) {
        if(CollectionUtils.isNotEmpty(records)) {
            threadPoolExecutor.execute(new MessageTask(records, messageService));
        }
    }

}
